#include "msgshowarea.h"
#include "mainwidget.h"
#include "debug.h"

#include <QTimer>

///////////////////////////////
// 消息展示区
///////////////////////////////
MsgShowArea::MsgShowArea(QScrollArea *parent)
    :QScrollArea(parent)
{
    this->setWidgetResizable(true);
    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    this->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width:2px; background-color: rbg(240, 240, 240); }");
    this->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { height: 0; }");
    this->setStyleSheet("QScrollArea { border: none; }");

    // 创建container
    _container = new QWidget();
    this->setWidget(_container);

    // 给container添加布局管理器
    QVBoxLayout *layout = new QVBoxLayout();
    layout->setSpacing(10);
    layout->setContentsMargins(0, 0, 0, 0);
    _container->setLayout(layout);

#if TEST_UI
    for (int i = 0; i < 30; i++)
    {
        model::UserInfo userInfo;
        userInfo._user_id = "111";
        userInfo._mail = "222222222";
        userInfo._nickname = "阿吉";
        userInfo._avatar = QIcon(":/resource/image/defaultAvatar.png");
        MessageInfo msg = MessageInfo::makeMessage(model::STRING_TYPE, QString("111"), userInfo, (QString("你好你好您好")).toUtf8());
        addMsg(true, msg);
        addMsg(false, msg);
    }
#endif
}

void MsgShowArea::addMsg(bool isLeft, const MessageInfo &msg)
{
    MessageItem *item = MessageItem::createMsgItem(isLeft, msg);
    _container->layout()->addWidget(item);
}

void MsgShowArea::addFrontMsg(bool isLeft, const MessageInfo &msg)
{
    MessageItem *item = MessageItem::createMsgItem(isLeft, msg);
    QVBoxLayout *layout = dynamic_cast<QVBoxLayout*>(_container->layout());
    layout->insertWidget(0, item);
}

void MsgShowArea::clear()
{
    QLayout *layout = _container->layout();
    if (!layout) return;
    for (int i = layout->count() - 1; i >= 0; i--)
    {
        QLayoutItem *item = layout->takeAt(i);
        if (item != nullptr && item->widget() != nullptr)
            delete item->widget();
    }
}

void MsgShowArea::scrollToEnd()
{
    QTimer *timer = new QTimer();
    connect(timer, &QTimer::timeout, this, [=](){
        int maxValue = this->verticalScrollBar()->maximum();
        this->verticalScrollBar()->setValue(maxValue);

        timer->stop();
        timer->deleteLater();
    });
    timer->start(500);
}

///////////////////////////////
// 一个消息元素
///////////////////////////////
MessageItem::MessageItem(bool isLeft)
    :_isLeft(isLeft) {}

MessageItem *MessageItem::createMsgItem(bool isLeft, MessageInfo msg)
{
    // 创建对象以及布局管理器
    MessageItem *msgItem = new MessageItem(isLeft);
    QGridLayout *layout = new QGridLayout();
    layout->setSpacing(10);
    layout->setContentsMargins(20, 10, 20, 0);
    msgItem->setMinimumHeight(100);
    msgItem->setLayout(layout);

    // 创建头像
    QPushButton *avatarBtn = new QPushButton();
    // avatarBtn->setFixedSize(QSize(40, 40));
    msgItem->setMinimumHeight(80);
    avatarBtn->setIconSize(QSize(40, 40));
    avatarBtn->setIcon(msg._sender._avatar);

    if (isLeft)
        layout->addWidget(avatarBtn, 0, 0, 2, 1, Qt::AlignLeft | Qt::AlignTop);
    else
        layout->addWidget(avatarBtn, 0, 1, 2, 1, Qt::AlignLeft | Qt::AlignTop);

    // 创建名字和时间
    QLabel *nameAndTimeLabel = new QLabel();
    nameAndTimeLabel->setText(msg._sender._nickname + "|" + msg._time);
    nameAndTimeLabel->setAlignment(Qt::AlignBottom);
    nameAndTimeLabel->setStyleSheet("QLabel { font-size: 12px; color: rgb(178, 178, 178); }");

    if (isLeft)
        layout->addWidget(nameAndTimeLabel, 0, 1);
    else
        layout->addWidget(nameAndTimeLabel, 0, 0, Qt::AlignRight);

    // 创建消息体
    QWidget *contentWidget = nullptr;
    switch (msg._message_type)
    {
    case model::STRING_TYPE:
        contentWidget = makeStringMsgItem(isLeft, QString::fromUtf8(msg._content));
        break;
    case model::IMAGE_TYPE:
        contentWidget = makeImageMsgItem();
        break;
    case model::FILE_TYPE:
        contentWidget = makeFileMsgItem();
        break;
    case model::SPEECH_TYPE:
        contentWidget = makeSpeechMsgItem();
        break;
    default:
        ERROR() << "消息类型错误: " << msg._message_type;
        break;
    }
    if (isLeft)
        layout->addWidget(contentWidget, 1, 1);
    else
        layout->addWidget(contentWidget, 1, 0);

    // 连接信号槽,创建用户点击头像的函数
    connect(avatarBtn, &QPushButton::clicked, msgItem, [=](){
        MainWidget *mainWidget = MainWidget::getInstance();
        UserInfoWidget *userInfoWidget = new UserInfoWidget(msg._sender, mainWidget);
        userInfoWidget->exec();
    });
    return msgItem;
}

QWidget *MessageItem::makeStringMsgItem(bool isLeft, const QString &content)
{
    MsgContentLabel *msgContentLabel = new MsgContentLabel(isLeft, content);
    return msgContentLabel;
}

QWidget *MessageItem::makeImageMsgItem()
{
    return nullptr;
}

QWidget *MessageItem::makeFileMsgItem()
{
    return nullptr;
}

QWidget *MessageItem::makeSpeechMsgItem()
{
    return nullptr;
}

MsgContentLabel::MsgContentLabel(bool isLeft, const QString &text)
    :_isLeft(isLeft)
{
    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    QFont font;
    font.setFamily("微软雅黑");
    font.setPixelSize(12);

    _label = new QLabel();
    _label->setText(text);
    _label->setFont(font);
    _label->setAlignment(Qt::AlignVCenter | Qt::AlignLeft);
    _label->setWordWrap(true);
    _label->setStyleSheet("QLabel { padding: 0 10px; line-height: 1.2; background: transparent; }");
    _label->raise();
    QHBoxLayout* layout = new QHBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(_label);
}

void MsgContentLabel::paintEvent(QPaintEvent *ev)
{
    (void)ev;
    // 获取到父元素的宽度
    QObject *parent = this->parent();
    if (!parent->isWidgetType())
        return;
    QWidget *pWidget = dynamic_cast<QWidget*>(parent);
    int width = pWidget->width() * 0.6;
    // 计算一行文本需要多宽
    QFontMetrics metrics(_label->font());
    int totalWidth = metrics.horizontalAdvance(_label->text());
    // DEBUG() << "totalWidth: " << totalWidth;
    // 计算所需行数
    int rows = (totalWidth / (width - 40)) + 1;

    if (rows == 1) // 如果得到的行数只有一行, 说明文本很窄, 拓宽一下
        width = totalWidth + 35;

    // 根据行数计算高度, 20表示上下各有10px边距
    int height = rows * (_label->font().pixelSize() *1.2) + 20;

    // 绘制圆角矩形和箭头
    QPainter painter(this);
    QPainterPath path;
    painter.setRenderHint(QPainter::Antialiasing);
    if (_isLeft)
    {
        painter.setPen(QPen(QColor(255, 255, 255)));
        painter.setBrush(QColor(255, 255, 255));

        painter.drawRoundedRect(10, 0, width, height, 10, 10);
        path.moveTo(10, 15);
        path.lineTo(0, 20);
        path.lineTo(10, 25);
        path.closeSubpath();
        painter.drawPath(path);

        _label->setGeometry(10, 0, width, height);
    }
    else
    {
        painter.setPen(QPen(QColor(137, 217, 97)));
        painter.setBrush(QColor(137, 217, 97));

        int leftPos = this->width() - width - 10;
        int rightPos = this->width() - 10;
        painter.drawRoundedRect(leftPos, 0, width, height, 10, 10);
        path.moveTo(rightPos, 15);
        path.lineTo(rightPos + 10, 20);
        path.lineTo(rightPos, 25);
        path.closeSubpath();
        painter.drawPath(path);

        _label->setGeometry(leftPos, 0, width, height);
    }
    // DEBUG() << "width: " << width << " height: " << height << " rows: " << rows;

    // 重新设置父元素高度
    pWidget->setFixedHeight(height + 50);
}

